package com.boyinet.imesh2json.viewmodel

import com.boyinet.imesh2json.bean.Index
import com.boyinet.imesh2json.bean.Template
import com.boyinet.imesh2json.model.IndexModel
import com.boyinet.imesh2json.netty.client.TransformClient
import com.boyinet.imesh2json.netty.server.NettyServerListener
import com.boyinet.imesh2json.repo.IndexRepository
import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport
import javafx.application.Platform
import javafx.beans.property.SimpleStringProperty
import javafx.beans.property.StringProperty
import javafx.collections.ObservableList
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.concurrent.CompletableFuture

@Component
class IndexViewModel {

    @Autowired
    lateinit var indexRepository: IndexRepository

    @Autowired
    lateinit var templateViewModel: TemplateViewModel

    @Autowired
    lateinit var nettyServerListener: NettyServerListener

    @Autowired
    lateinit var transformClient: TransformClient

    val current: IndexModel by lazy {
        val default = indexRepository.findById(1).orElse(Index(1).apply {
            port = 8000
            type = 0
        })
        IndexModel().apply {
            id.value = default.id
            type.value = default.type
            templateId.value = default.templateId
            port.value = default.port.toString()
            url.value = default.url
        }

    }

    val templateItems: ObservableList<Template> by lazy {
        templateViewModel.lists
    }

    val statusStr: StringProperty = SimpleStringProperty("监 听")

    var status = false

    fun save() {
        indexRepository.save(Index(current.id.value).apply {
            type = current.type.value
            templateId = current.templateId.value
            port = current.port.value.toInt()
            url = current.url.value
        })
    }

    fun startServer() {
        CompletableFuture.runAsync {
            save()
            //nettyServerListener.startNettyServer(current.port.value.toInt())
        }.thenRun {
            val url = current.url.value
            val urls = url.split(":")
            transformClient.connect(urls[0], urls[1].toInt())
        }.whenComplete { _, u ->
            if (u == null) {
                status = true
                Platform.runLater {
                    statusStr.value = "断 开"
                }
            } else {
                System.err.println(u)
                //stopServer()
                status = false
                Platform.runLater {
                    statusStr.value = "监 听"
                }
            }
        }
    }

    fun stopServer() {
        //nettyServerListener.shutdown()
        transformClient.disconnect()
        status = false
        statusStr.value = "监 听"
    }

}